#!/usr/bin/env bash

# JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-12.jdk/Contents/Home

JAVA_VERSION=$(java -version 2>&1 | head -n 1 | cut -f 3 -d " ")

if [ -z "$JAVA_HOME" ] || [ "$JAVA_VERSION" != "\"12.0.2\"" ]; then
    echo "Set JAVA_HOME to Adopt OpenJDK 12.0.2. Download from https://adoptopenjdk.net/archive.html?variant=openjdk12&jvmVariant=hotspot."
    exit 1
fi

rm -rf classes
mkdir -p classes
rm -rf /tmp/transit
mkdir -p /tmp/transit

( if [ ! -d /tmp/jdk ]; then
    mkdir -p /tmp/jdk
    cd /tmp
    git clone https://github.com/openjdk/jdk.git
    cd /tmp/jdk
    ## note, it's not important that this succeeds, cant't get it to work on Mojave
    bash configure
else
    cd /tmp/jdk
    git pull
fi

cd /tmp/jdk
make java.base-gensrc )

clojure -R:clojure-1.10.1 -C:extract -e "(compile 'clj-kondo.impl.ExtractJava)"
read -r -d '' source_path <<EOF
/tmp/jdk/src/java.base/share/classes:/tmp/jdk/src/java.base/unix/classes\
:/tmp/jdk/src/java.base/macosx/classes\
:/tmp/jdk/build/macosx-x86_64-server-release/support/gensrc/java.base
EOF

clojure -R:clojure-1.10.1 -A:extract -m clj-kondo.impl.ExtractJava "/tmp/transit" \
        "-public" "--source-path" "$source_path" \
        "java.lang" "java.math"

for class in "Boolean" "Byte" "CharSequence" "Character" \
             "Double" "Integer" "Long" "Math" "String" \
             "System" "Thread"; do \
    cp "/tmp/transit/java.lang.$class.transit.json" "resources/clj_kondo/impl/cache/built_in/clj"
done

for class in "BigInteger" "BigDecimal"; do \
    cp "/tmp/transit/java.math.$class.transit.json" "resources/clj_kondo/impl/cache/built_in/clj"
done
